﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TuChongPicView.Common;
using TuChongPicView.Entity;
using TuChongPicView.Service;

namespace TuChongPicView
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private BackgroundWorker bgWorker = new BackgroundWorker();
        private List<TagResponse> postList = new List<TagResponse>();
        private BlockingCollection<Post> blockingCollection = new BlockingCollection<Post>();
        private int page = 1;
        private int count = 20;
        private String tagName = null;
        private ImgView imgView = null;

        public MainWindow()
        {
            InitializeComponent();
            Init();
        }
        private void Init()
        {
            bgWorker.WorkerReportsProgress = false;
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.DoWork += BgWorker_DoWork;

            imgView = new ImgView(blockingCollection);
            imgView.NeedAddImgEvent += ImgView_NeedAddImgEvent;
            imgView.ExitViewEvent += ImgView_ExitViewEvent;
            this.picTag.KeyDown += PicTag_KeyDown;
        }

        private void PicTag_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            log.Debug("回车操作");
            ViewButton_Click(sender, e);
        }

        private void ImgView_ExitViewEvent()
        {
            log.Debug("接收到图片展示退出操作");
            bgWorker.CancelAsync();
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.Show();
            this.Activate();
            imgView.Hide();
        }

        private void ImgView_NeedAddImgEvent()
        {
            log.Debug("收到通知添加网络图片");
            runBackGroundWork();
        }

        private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            String reqUrl = Constants.URL_TAG_POSTER + tagName + "/posts" + "?page=" + page + "&count=" + count + "&order=weekly";
            Dictionary<string, string> param = new Dictionary<string, string>();
            TagResponse response = HttpService<TagResponse>.get(reqUrl, param);
            if (response != null && response.postList != null)
            {
                foreach (Post p in response.postList)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    if (p.images.Count >= 1) {
                        for (int i = 0; i < p.images.Count; i++)
                        {
                            if (backgroundWorker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }
                            String url = Constants.URL_IMG_HIGHT + p.author_id + "/f/" + p.images[i].img_id_str + ".jpg";
                            String fileName = p.author_id + "_" + p.images[i].img_id_str + ".jpg";

                            log.Debug("URL:" + url + " FileName:" + fileName);
                            WebClient mywebclient = new WebClient();
                            try
                            {
                                if (!Directory.Exists("pic"))
                                {
                                    Directory.CreateDirectory("pic");
                                }
                                mywebclient.DownloadFile(url, "pic/" + fileName);
                                p.images[i].localFileName = fileName;
                            }
                            catch (Exception ex)
                            {
                                log.Error("图片下载异常", ex);
                            }
                        }
                        blockingCollection.Add(p);
                    }
                }
                page += 1;
            }
        }

        private void ViewButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.picTag.Text == null || picTag.Text == "")
            {
                System.Windows.MessageBox.Show("请输入标签");
            }
            else
            {
                string encodeTag = HttpUtility.UrlEncode(this.picTag.Text);
                if (encodeTag != this.tagName) {
                    this.page = 1;
                    if (blockingCollection.Count > 0) {
                        log.Debug("清理 blockingCollection");
                    }
                    imgView.ClearQueue();
                }
                this.tagName = encodeTag;
                runBackGroundWork();
                imgView.Show();
                imgView.startTimer();
                this.Hide();
            }
        }

        private void runBackGroundWork() {
            if (!bgWorker.IsBusy)
            {
                log.Debug("开始执行后台任务");
                bgWorker.RunWorkerAsync();
            }
        }

        private void picTag_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.picTag.Text == "请输入标签") {
                this.picTag.Text = "";
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }
    }
}
